<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 商品列表 -->
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
        <div>选择商品分类：
           <el-cascader
            clearable
            style="width: 300px"
            v-model="changeArr"
            :options="cateList"
            :props="props"
            @change="handleChange">
          </el-cascader>
        </div>
        <el-tabs v-model="activeName" @tab-click="tabsHandleClick">
          <!-- 动态参数 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="showDialog" type="primary" size="mini" :disabled="isBtnFlag">添加参数</el-button>
            <div>
              <el-table
                border
                stripe
                :data="dynamicData"
                style="width: 100%">
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag closable @close="removeTag(i,scope.row)" v-for="(item, i) in scope.row.attr_vals" :key="i">{{ item }}</el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)">
                    </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <!-- 静态属性 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button @click="showDialog" type="primary" size="mini" :disabled="isBtnFlag">添加属性</el-button>
            <div>
              <el-table
                border
                stripe
                :data="staticData"
                style="width: 100%">
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag closable @close="removeTag(i,scope.row)" v-for="(item, i) in scope.row.attr_vals" :key="i">{{ item }}</el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)">
                    </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
    </el-card>

<!-- 添加动态参数和静态参数对话框 -->
     <el-dialog
      :title="paramsStr + paramsText"
      :visible.sync="addParamsFlag"
      @close="addParamsClose"
      width="50%">
      <el-form ref="addParamsForm" :model="addParamsForm" :rules="addParamsRules" label-width="80px">
        <el-form-item :label="paramsText" prop="addParamsStr">
          <el-input v-model="addParamsForm.addParamsStr"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsFlag = false">取 消</el-button>
        <el-button v-if="reverseFlag" @click="addParams" type="primary">确 定</el-button>
        <el-button v-else @click="editParams" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 选择的数据
      changeArr: [],
      // 级联选择器的数据
      cateList: [],
      // 级联选择器的配置对象
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // tabs绑定参数
      activeName: 'many',
      // 动态属性数据
      dynamicData: [],
      // 静态属性数据
      staticData: [],
      // 添加参数对话框
      addParamsFlag: false,
      // 添加或修改参数字段
      addParamsForm: {
        addParamsStr: ''
      },
      // 验证添加参数和属性的规则
      addParamsRules: {
        addParamsStr: [
          { required: true, message: '请输入字段名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 设置相反的字段使对话框的功能不同
      reverseFlag: true,
      // 编辑功能的参数id
      editAttrId: 0
    }
  },

  created () {
    this.getCateList()
  },
  // 计算属性
  computed: {
    // 设置按钮是否被禁用
    isBtnFlag () {
      return this.changeArr.length !== 3
    },
    // 请求三级参数配置对象的参数，在此写其实没有必要
    cateId () {
      return this.changeArr.length === 3 ? this.changeArr[2] : null
    },
    // 添加对话框提示文本
    paramsText () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    },
    paramsStr () {
      return this.reverseFlag ? '添加' : '编辑'
    }
  },

  methods: {
    // 获取商品数据
    async getCateList () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 选中值的时候发生的回调
    handleChange () {
      this.getParams()
    },
    // 切换标签页
    tabsHandleClick () {
      this.getParams()
    },
    // 抽离发起参数请求函数
    async getParams () {
      if (this.changeArr.length !== 3) {
        this.changeArr = []
        this.staticData = []
        this.dynamicData = []
        return
      }
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(value => {
        value.attr_vals = value.attr_vals.length > 0 ? value.attr_vals.split(' ') : []
        value.inputVisible = false
        value.inputValue = ''
      })
      this.activeName === 'only' ? this.staticData = res.data : this.dynamicData = res.data
    },
    // 添加对话框的显示
    showDialog () {
      this.addParamsFlag = true
      this.reverseFlag = true
    },
    // 添加参数
    addParams () {
      this.$refs.addParamsForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.addParamsStr,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParams()
        this.addParamsFlag = false
      })
    },
    addParamsClose () {
      this.$refs.addParamsForm.resetFields()
    },
    // 删除参数
    removeParams (row) {
      this.$confirm('此操作将删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParams()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 修改参数对话框
    editDialog (row) {
      this.addParamsFlag = true
      this.reverseFlag = false
      this.editAttrId = row.attr_id
      this.addParamsForm.addParamsStr = JSON.parse(JSON.stringify(row)).attr_name
    },
    // 确认修改参数
    editParams () {
      this.$refs.addParamsForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editAttrId}`, {
          attr_name: this.addParamsForm.addParamsStr,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParams()
        this.addParamsFlag = false
      })
    },
    // 控制让添加tag时变成input
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 控制让添加tag时变成button
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length <= 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      const valsArr = [...row.attr_vals]
      this.saveAttrValues(row, valsArr)
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
    },
    // 添加和删除tag标签的处理函数
    async saveAttrValues (row, valsArr) {
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: valsArr.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 删除tag标签
    removeTag (i, row) {
      row.attr_vals.splice(i, 1)
      const valsArr = row.attr_vals
      this.saveAttrValues(row, valsArr)
    }
  }
}
</script>

<style scoped lang='less'>
.el-alert {
  margin-bottom: 20px;
}
.el-tag {
  margin: 7px;
}
.input-new-tag {
  width: 90px;
}
</style>
